package com.kl.student;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.junit.Test;

/**
 * 学生类中关联着一个老师，将这个学生类的XML文件解析为学生类
 */
public class StudentParseDemo {

    //创建XmlMapper对象，用于实体与json和xml之间的相互转换
    private static final XmlMapper XML_MAPPER;

    static {
        XML_MAPPER = new XmlMapper();
        //反序列化时，若实体类没有对应的属性，是否抛出JsonMappingException异常，false忽略掉
        XML_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //序列化是否绕过根元素，true，则以类名为根元素
        XML_MAPPER.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
        //忽略空属性
        XML_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //XML标签名:使用骆驼命名的属性名，
        XML_MAPPER.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE);
        //设置转换模式
        XML_MAPPER.enable(MapperFeature.USE_STD_BEAN_NAMING);
    }

    @Test
    public void test1() throws JsonProcessingException {
        Student s = new Student();
        s.setStudentNo("202101001");
        s.setStudentName("张三");
        Teacher teacher = new Teacher();
        teacher.setName("老王老师");
        teacher.setAge(50);
        s.setTeacher(teacher);
        //实体类解析为xml的字符串（理论上可以将任意类型解析为xml字符串）
        String xmlStr = XML_MAPPER.writeValueAsString(s);
        /*
         * <Student>
         *     <StudentNo>202101001</StudentNo>
         *     <StudentName>张三</StudentName>
         *     <Teacher>
         *         <Name>老王老师</Name>
         *         <Age>50</Age>
         *     </Teacher>
         * </Student>
         */
        System.out.println(xmlStr);
        //把字符串转换为实体类
        Student student = XML_MAPPER.readValue(xmlStr, Student.class);
        System.out.println(student);//Student(studentNo=202101001, studentName=张三)
    }

    @Test
    public void test2() throws JsonProcessingException {
        String s = "<Student>\n" +
                "    <StudentNo>202101001</StudentNo>\n" +
                "    <StudentName>张三</StudentName>\n" +
                "    <Teacher>\n" +
                "        <Name>老王老师</Name>\n" +
                "        <Age>50</Age>\n" +
                "    </Teacher>\n" +
                "</Student>";
        Student student = XML_MAPPER.readValue(s, Student.class);
        System.out.println(student);
    }
}    